package com.example.boot4redis.service.impl;

import com.example.boot4redis.entity.Book;
import com.example.boot4redis.service.BookService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;



@Service
public class BookServiceImpl implements BookService {

    private static final Logger logger = LoggerFactory.getLogger(BookServiceImpl.class);


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate redisTemplate;


    public String saveRedis(){

        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        valueOperations.set("StringKey2","李四");
        String key1 = valueOperations.get("StringKey2");
        System.out.println(key1);//张三
        return "save string is ok";
    }

    @Override
    public String saveRedisObject() {

        Book book = new Book();
        book.setBookName("momopake");
        book.setPrice(new BigDecimal(123));
        book.setAuthor("chen feilong");
        book.setStock(15);
        book.setDescription("人文");

        redisTemplate.setKeySerializer(new StringRedisSerializer());

        //把值作json序列化
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Book.class));

        redisTemplate.opsForValue().set("myBook",book);


        //将存到redis的book取出打印
        Book obj = (Book) redisTemplate.opsForValue().get("myBook");
        System.out.println("存到redis的book 的字段"+obj.getBookName());
        System.out.println("存到redis的book"+obj.toString());

        return "save object is ok";
    }


}
